package com.acane.instagram.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;

@Service
public class FileStorageService {

    public String storeFile(MultipartFile file, String fileName) throws IOException {
        // 打印真实 Content-Type 用于调试
        System.out.println("真实 Content-Type: " + file.getContentType());

        // 放宽校验逻辑（允许常见图片和视频类型）
        List<String> allowedTypes = Arrays.asList(
                "image/jpeg",
                "image/png",
                "image/gif",
                "image/webp",
                "video/mp4",
                "video/quicktime",
                "video/avi",
                "video/mpeg",
                "video/x-msvideo",
                "video/x-matroska"
        );

        if (!allowedTypes.contains(file.getContentType())) {
            throw new IllegalArgumentException("仅支持 JPG/PNG/GIF/WEBP/MP4/QUICKTIME/AVI/MPEG/X-MSVIDEO/X-MATROSKA 格式");
        }

        // 2. 创建目标目录
        String uploadDir = "E:\\uploads\\";
        Path targetPath = Paths.get(uploadDir).toAbsolutePath().normalize();
        if (!Files.exists(targetPath)) {
            Files.createDirectories(targetPath);
        }

        // 3. 保存文件
        Path filePath = targetPath.resolve(fileName);
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
        }

        return filePath.toString();
    }
}
